package com.hongri.recyclerview.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Environment;
import com.hongri.recyclerview.MyApplication;
import com.hongri.recyclerview.utils.Logger;
import com.hongri.recyclerview.utils.ToastUtil;

/**
 * Created by zhongyao on 2017/7/19.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private String TAG = CrashHandler.class.getSimpleName();

    private static CrashHandler crashHandler;
    private MyApplication application;
    private static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CrashTest/log/";
    private static final String FILE_NAME = "crash";
    private static final String FILE_NAME_FUFFIC = ".txt";
    /**
     * 系统默认的UncaughtException处理类
     */
    private UncaughtExceptionHandler mDefaultHandler;
    private Context mContext;

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if (!handleException(throwable) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, throwable);
        } else {
            // Sleep一会后结束程序
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Logger.e(TAG + " Error : " + e);
            }

            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(10);
        }
    }

    public static CrashHandler getInstance() {
        if (crashHandler == null) {
            crashHandler = new CrashHandler();
        }
        return crashHandler;
    }

    public void init(Context context) {
        application = (MyApplication)context;
        mContext = context.getApplicationContext();
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        ex.printStackTrace();
        // 收集设备信息
        //collectCrashDeviceInfo(wanbuApplication);
        // 保存错误报告文件
        //saveCrashInfoToFile(ex);
        // 发送错误报告到服务器
        //sendCrashReportsToServer(wanbuApplication);
        Logger.d("Exception:" + ex);

        /**
         * 将异常crash 信息导入到SD卡
         */
        dumpExceptionToSDCard(ex);
        /**
         * 将异常信息传入到后台Server（实际开发中会用到）
         */
        //updateExcetionToServer(ex);

        return true;
    }

    /**
     * 将异常crash 信息导入到SD卡，供开发人员分析查看
     *
     * @param ex
     */
    private void dumpExceptionToSDCard(Throwable ex) {
        try {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Logger.d("没有SD卡");
                return;
            }
            File dir = new File(PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            long current = System.currentTimeMillis();
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
            //File file = new File(PATH + FILE_NAME + time + FILE_NAME_FUFFIC);
            File file = new File(dir,"hongrilog.txt");
            if (!file.exists()) {
                file.createNewFile();
            }

            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            pw.println(time);
            dumpPhoneInfo(pw);
            pw.println();
            ex.printStackTrace(pw);
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
            Logger.d("dump crash info failed");
            ToastUtil.ShowBottomShort(mContext, "dump crash info failed");
        }

    }

    private void dumpPhoneInfo(PrintWriter pw) {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(),
                PackageManager.GET_ACTIVITIES);
            pw.print("APP Version:");
            pw.print(packageInfo.versionName);
            pw.print("_");
            pw.print(packageInfo.versionCode);

            //Android 版本号
            pw.print("OS Verison:");
            pw.print(VERSION.RELEASE);
            pw.print("_");
            pw.print(VERSION.SDK_INT);

            //手机制造商
            pw.print("Vendor:");
            pw.print(Build.MANUFACTURER);

            //手机型号
            pw.print("Model:");
            pw.print(Build.MODEL);

            //CPU架构
            pw.print("CPU_ABI:");
            pw.print(Build.CPU_ABI);

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
